#!/bin/bash

fail() {
    local _red="\\033[1;31m"
    local _normal="\\033[0;39m"
    [ -n "$*" ] && printf "${_red}$*${_normal}\n"
    exit 1
}

print_message() {
    printf "%s\n" "${1}"
}

success() {
    print_message "$*"
    exit 0
}

SYSTEMD_NETWORK_CONF_DIR="/etc/systemd/network"

[ $# -ne 1 ] && fail "Incorrect args: ifup <ifname>"

interface=$1

print_message "Make sure the interface is down or not assigned any IP"

output=`ip addr show $interface`

#check if the interface is up
echo $output | grep -o "state UP"
isupret=$?
echo $output | grep -o "inet [0-9]*\.[0-9]*\.[0-9]*\.[0-9]*"
hasip=$?

[ $isupret -eq 0 -a $hasip -eq 0 ] && success "The interface is already up and assigned an IP"

print_message "$interface is DOWN or not assigned an IP. Bringnig $interface up..."

manualfilename=`ls ${SYSTEMD_NETWORK_CONF_DIR}/*$interface*.network.manual 2>/dev/null`
if [[ -z  $manualfilename ]] ; then
    print_message "Can not find the manual filename, let us search for the auto filename"
    filename=`ls ${SYSTEMD_NETWORK_CONF_DIR}/*$interface*.network 2>/dev/null`
    [[ -z  $filename ]] && fail "Can not find network interface file"
else
    filename=$manualfilename
fi

# Trying to parse the address from the file
while read line
do 
    key=`echo $line | cut -d'=' -f1`
    if [ "$key" = "Address" ]
    then 
        address=`echo $line | cut -d'=' -f2 | cut -d'/' -f1`
    fi 
done < $filename

[[ -z  $address ]] && print_message "Did not find address in the configuration file, may be it's dhcp, will not check for duplicates"

#flush the adress
ip addr flush $interface || fail "Cannot flush IP address for $interface"

#Bring the interface up
ip link set dev $interface up || fail "Cannot bring $interface up"

if [[ -n  $address ]] ; then
    if [[ $address =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        echo "Performing duplicate address check for IPv4 address $address"
        arping -D -q -I $interface -c 2 $address
        retval=$?
        [ $retval -eq 1 ] && fail "Error: IP already exists in the network"
        [ $retval -eq 2 ] && fail "Cannot procceed. $interface is down"
        [ $retval -ne 0 ] && fail "Unknown error!"
    else
        echo "Skipping duplicate address check for IPv6 address $address"
    fi
fi

print_message "Everything is good, IP is not assigned elsewhere, will restart systemd-networkd"

if [[ -n $manualfilename ]] ; then
    autofilename="${manualfilename%.*}"
    print_message "The interface is set to manual, will rename $manualfilename to $autofilename"
    mv $manualfilename $autofilename
    print_message "Restarting systemd-networkd"
    systemctl restart systemd-networkd
    retval=$?
    print_message "Rename back from $manualfilename to $autofilename"
    mv $autofilename $manualfilename
    [ $retval -eq 0 ] || fail "Failed to restart systemd-networkd"
else
    systemctl restart systemd-networkd || fail "Failed to restart systemd-networkd"
fi
exit 0
